import ajax from 'uni-ajax';
import code from './Code.js'

// 创建实例
let instance = ajax.create({
	baseURL: import.meta.env.VITE_APP_BASE_API,
	timeout: 10000,
	// 请求头
	headers: {
		'Content-Type': 'application/json',
	}
})

// 添加请求拦截器
instance.interceptors.request.use(
	config => {
		config.headers.token = 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjgzMzgzNzc5LTYxYjEtNDdjYS04ODY1LTkyMmYyMjM4MTllZCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.rPi60Rr6KmjsKn0yPi_GXHjGL4WMPx4MOqq2EtA8-jLrJSrOd0w3irWF0xyytXMsn1qwQtRIalNBXnekWtbqNQ';
		config.headers.Authorization = 'eyJhbGciOiJIUzUxMiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VyX2tleSI6IjgzMzgzNzc5LTYxYjEtNDdjYS04ODY1LTkyMmYyMjM4MTllZCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.rPi60Rr6KmjsKn0yPi_GXHjGL4WMPx4MOqq2EtA8-jLrJSrOd0w3irWF0xyytXMsn1qwQtRIalNBXnekWtbqNQ';
		config.headers['Content-Type'] = 'application/json;charset=utf-8';
		return config
	},
	error => {
		// 对请求错误做些什么
		return Promise.reject(error)
	}
)

// 添加响应拦截器
instance.interceptors.response.use(
	(response) => {
		console.log(response)
		const { data } = response
		const { code, msg } = data
		
		uni.showToast({ icon: 'none', position: 'bottom', title: response.data.msg || code[response.statusCode] })
		
		if (code === 200) return response
		if (code === 99) {
		  uni.reLaunch({ url: '/pages/index/index' })
		}
		
		return Promise.resolve(response)
	},
	error => {
		console.log(error)
		// 对响应错误做些什么
		const { response } = error;
		if (response) {
			return Promise.reject(response.data);
		}
		return Promise.reject(error);
	}
)

export default instance